package pl.koszolko.documentclustering.cluster.document;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.language.Soundex;

import pl.koszolko.documentclustering.dao.Author;
import pl.koszolko.documentclustering.dao.Document;

public class DocumentClusteringBySundexAuthor extends
		DocumentClusteringByAuthor {
	private static final long serialVersionUID = 1L;
	
	/** Lista nazwisk autorow przetworzonych przez algorytm soundex */
	private List<String> soundexAuthors;
	
	public DocumentClusteringBySundexAuthor(Document document) {
		super(document);
		createSoundexAuthorRepresentation();
	}

	private void createSoundexAuthorRepresentation() {
		soundexAuthors = new ArrayList<String>();
		Soundex soundex = new Soundex();
		for(Author a : getAuthors()) {
			soundexAuthors.add(soundex.soundex(a.getName()));
		}
	}
	
	@Override
	public double countSimilarity(DocumentForClustering document) {
		if(document instanceof DocumentClusteringByAuthor) {
			return countSimilarityBySundexAuthor((DocumentClusteringBySundexAuthor) document);
		}
		throw new RuntimeException("Obiekt document posiada niewlasciwy typ");
	}

	private double countSimilarityBySundexAuthor(DocumentClusteringBySundexAuthor document) {
		double commonAuthors = 0;
		double allAuthors = soundexAuthors.size();
		
		for(String a :document.soundexAuthors) {
			if(soundexAuthors.contains(a)) {
				++commonAuthors;
			} else {
				++allAuthors;
			}
		}
		
		if(allAuthors == 0) {
			return 0D;
		}
		
		return commonAuthors/allAuthors;
	}
	
	 

}
